from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser, OAuthSinaUser
from oauth.utils import check_access_token
from users.models import User

"""
说明：要绑定ＱＱ号，不单单要获取到　openid,
１．还要给用户发送短信进行验证，要给用户发送短信，
就需要用户的手机号码［为什么？因为用户可能以前没注册，直接使用ＱＱ进行登陆］
２．判断完短信验证码就要判断用户是否存在，如果用户已存在，直接判断密码，
密码正确直接绑定openid，然后跳转登陆
绑定用户页面传来的字段：
access_token(openid),
手机号，密码，短信验证码
用户填写上的手机号，要判断是否已存在，不能重复注册
"""


class OauthQQUserSerializer(serializers.Serializer):

    # 字段验证,选项验证
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    # 内容验证
    def validate(self, attrs):
        # 1.验证　access_token
        access_token = attrs['access_token']
        openid = check_access_token(access_token)
        if openid is None:
            raise serializers.ValidationError('openid已过期')
        attrs['openid'] = openid
        # 2.短信验证
        sms_code = attrs.get('sms_code')
        redis_conn = get_redis_connection('code')
        mobile = attrs.get('mobile')
        redis_code = redis_conn.get('sms_%s' % mobile)
        # 短信验证码存储到 redis 时设置了有效期，验证是否过期
        if redis_code is None:
            raise serializers.ValidationError('短信验证码已过期')
        # 从redis 获取的数据是二进制，要解码
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('验证码错误')

        # 3.查询手机号是否存在,模型类　get 查询，抛出异常　DoesNotExist
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存在，用户没注册过，应该直接注册，后边写

            pass

        else:
            # 如果注册过，就要校验密码是否正确
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码不正确')
            attrs['user'] = user
        return attrs

    """
    创建用户，要进行逻辑判断
    用户是否存在,不存在就创建用户，

    """
    def create(self, validated_date):
        user = validated_date.get('user')
        if user is None:
            # 说明用户手机号没注册过
            # 将手机号作为用户名进行注册
            user = User.objects.create(
                username=validated_date.get('mobile'),
                mobile=validated_date.get('mobile'),
                password=validated_date.get('password')
            )
            user.set_password(validated_date.get('password'))
            user.save()

        # user = OAuthQQUser.objects.create(
        #     user=user,
        #     openid=validated_date.get('openid')
        # )
        # return user(self.reuse)
        return self.reuse(user, validated_date)

    def reuse(self, user, validated_date):
        user = OAuthQQUser.objects.create(
            user=user,
            openid=validated_date.get('openid')
        )
        return user


class OAuthSinaUserSerializer(OauthQQUserSerializer):

    def reuse(self, user, validated_date):
        user = OAuthSinaUser.objects.create(
            user=user,
            access_token=validated_date.get('openid')
        )
        return user

